package edu.cuit.jead.mynetdisk.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import edu.cuit.jead.mynetdisk.common.Code;
import edu.cuit.jead.mynetdisk.common.Result;
import edu.cuit.jead.mynetdisk.entity.Fileinfo;
import edu.cuit.jead.mynetdisk.entity.User;
import edu.cuit.jead.mynetdisk.exception.AppException;
import edu.cuit.jead.mynetdisk.service.Fileservice;
import edu.cuit.jead.mynetdisk.service.UserService;
import edu.cuit.jead.mynetdisk.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private Fileservice fileservice;

    private String projectDir=System.getProperty("user.dir");
    private String datepath=projectDir.substring(0, projectDir.lastIndexOf("\\"));
    private String adress="\\files\\";

    @PostMapping("/login")
    public Object login(@RequestBody Map<String,String> loginParam){
        String email=loginParam.get("email");
        String password=loginParam.get("password");
        System.out.println("email:"+email);
        User user = new User();
        String token = TokenUtil.sign(user);
        user.setToken(token);
        user = userService.login(email,password,token);
        JSONObject jsonObject = new JSONObject();
        if(user!=null){
            jsonObject.put("code",200);
            jsonObject.put("msg","success");
            jsonObject.put("token",token);
            jsonObject.put("email",user.getEmail());
            jsonObject.put("username",user.getUsername());
            System.out.println(jsonObject);
            return jsonObject;
        }else {
            throw new AppException(Code.WRONG_EMAIL_OR_PASSWORD);
        }
    }
    @PostMapping("/register")
    public Object register(@RequestBody Map<String,String> registerParam) {
        User newuser=new User();
        newuser.setEmail(registerParam.get("email"));
        newuser.setPassword(registerParam.get("password"));
        newuser.setUsername(registerParam.get("username"));
        Integer choose = userService.register(newuser);
        if( choose==null){
            Result.error(500,"系统错误");
        }
        else if(choose==1){
            throw new AppException(Code.USED_EMAIL);
        }
        else if(choose==2){
            throw new AppException(Code.USED_USERNAME);
        }
        throw new AppException(Code.REGISTER_SUCCESS);
    }
    @PostMapping("/userdata")
    public Object userdata(@RequestBody Map<String,String> dataParam){
        System.out.println("email:"+dataParam.get("email"));
        JSONObject result = new JSONObject();
        JSONObject storageinfo=new JSONObject();
        User user = new User();
        user=userService.userdata(dataParam.get("email"));
        System.out.println(user);
        if(user==null){
            Result.error(500,"系统错误");
        }
        //传user
        result.put("id",user.getId().toString());
        result.put("username",user.getUsername());
        result.put("password",user.getPassword());
        result.put("email",user.getEmail());
        result.put("token",user.getToken());
        result.put("avatar","file://"+user.getAvatar().replace("\\","/"));
        //传storage

        storageinfo.put("userdStorage",user.getUsedspace()/1024*1024*1024);
        storageinfo.put("totalStorage",user.getTotalspace()/(1024*1024*1024));
        result.put("storageInfo",storageinfo);
        List<Fileinfo> files= new ArrayList<>();
        files = fileservice.filedata(dataParam.get("email"));
        if(files==null){
            System.out.println("no file in user");
        }
        //传file
        List<JSONObject> listjson=new ArrayList<>();
        for(Fileinfo singleFile:files){
            JSONObject singleFiledata=new JSONObject();
            singleFiledata.put("fileName",singleFile.getPath().substring(singleFile.getPath().lastIndexOf("\\")+1));
            singleFiledata.put("fileType",singleFile.getPath().substring(singleFile.getPath().lastIndexOf(".")+1));
            Long size = singleFile.getSize();
            if(size>=1073741824){
                singleFiledata.put("fileSize",size/1073741824+"GB");
            }
            else if(size>=1048576){
                singleFiledata.put("fileSize",size/1048576+"MB");
            }
            else if(size>=1024){
                singleFiledata.put("fileSize",size/1024+"KB");
            }
            else{singleFiledata.put("fileSize",size+"B");}
            singleFiledata.put("lsatModified",singleFile.getLastedit());
            if(singleFile.getCollected()==1){
                singleFiledata.put("isStarred",true);
            }
            else{
                singleFiledata.put("isStarred",false);
            }
            if(singleFile.getShared()==1){
                singleFiledata.put("isShared",true);
            }
            else{
                singleFiledata.put("isShared",false);
            }
            if(singleFile.getRecycled()==1){
                singleFiledata.put("isDeleted",true);
            }
            else{
                singleFiledata.put("isDeleted",false);
            }
            listjson.add(singleFiledata);
        }
        result.put("fileList",listjson);
        System.out.println(result);
        return result;
    }

    @PostMapping("/changepictrue")
    public Result changepictrue(@RequestPart("file") MultipartFile file, @RequestParam("email") String email) throws IOException, IOException {
         System.out.println("email:"+email);
        if (file.isEmpty()) {
            return Result.error(Code.FILE_NOT_EXIST);
        }
        String filePath = datepath+adress+"pictures\\";
        if (!FileUtil.exist(filePath)) {//如果文件路径不存在就创建
            FileUtil.mkdir(filePath);
        }
        String fileName = file.getOriginalFilename();//文件的原始名称
        //String mainName = FileUtil.mainName(fileName);//文件的主要名称
        //String extName = FileUtil.extName(fileName);//文件的后缀名
        File savefile1 = new File(filePath + email +".jpg");
        File savefile2 = new File( "E:\\java\\java_project\\mynetdisk-vue6\\public\\" + email +".jpg");
        if(savefile1.exists()){//如果当前上传文件已经存在了，就要求删除文件
            savefile1.delete();
        }
        if(savefile2.exists()){//如果当前上传文件已经存在了，就要求删除文件
            savefile2.delete();
        }

        //写入文件
        byte[] bytes =file.getBytes();
        FileUtil.writeBytes(bytes, filePath+email+".jpg");
        FileUtil.writeBytes(bytes, "E:\\java\\java_project\\mynetdisk-vue6\\public\\"+email+".jpg");
        String url= "http://localhost:5080/files/download/pictures/"+fileName;
        System.out.println(filePath+email+".jpg");
        userService.changePicture(filePath+email+".jpg",email);
        return Result.success(url);
    }
    @PostMapping("/update-username")
    public Object updateUserName(@RequestBody Map<String,String> params){
        String username = params.get("username");
        System.out.println("username:"+username);
        String email = params.get("email");
        User user = new User();
        user = userService.findUserByName(username);
        if(user!=null){
            return Result.error(201,"用户名已存在");
        }
        Integer result = userService.updateUsername(username,email);
        if(result==null){
            Result.error(500,"更新失败");
        }
        JSONObject res = new JSONObject();
        res.put("code",200);
        System.out.println(res);
        return Result.error(200,"成功");
    }
    @PostMapping("/update-password")
    public void updatePassword(@RequestBody Map<String,String> params){
        System.out.println("params:"+params);
        String password = params.get("newpassword");
        String email= params.get("email");
        Integer result = userService.updatePassword(password,email);
    }
}
